//
// Created by konglinglong on 2020/9/6.
//

#ifndef CSP_LIB_CSP_INCLUDE_COMMON_COMMDEF_H
#define CSP_LIB_CSP_INCLUDE_COMMON_COMMDEF_H

#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/socket.h>
#include "ppvaMacro.h"
#include "metaMacro.h"
#include "bfMacro.h"

#define CSP_RC_OK  (0)
#define CSP_RC_ER  (-1)

#define TRUE  (1)
#define FALSE (0)

#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif

#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif

#define CSP_MODULE_INITIALIZED   1
#define CSP_MODULE_UNINITIALIZED 0

#define CEIL_DIVIDE_INT(a, b) (((a) + ((b) - 1)) / (b))

#define MEMORY_BARRIER() __sync_synchronize()
#define FETCH_AND_ADD(a, b) __sync_fetch_and_add(a, b)
#define FETCH_AND_SUB(a, b) __sync_fetch_and_sub(a, b)
#define COMPARE_AND_SWAP(a, b, c) __sync_bool_compare_and_swap(a, b, c)
#define FETCH_AND_SUB_SAFE(a, b) FETCH_AND_SUB(a, (b) <= *(a) ? (b) : *(a))

#define MEM_CHECK_FLAG  0x11332244
#define CALC_ALIGN_SIZE(n, align_size) (((n) + (align_size - 1)) & (~(align_size - 1)))

#define CONTAINER_OF(ptr, type, member) \
    ({const typeof(((type *)0)->member) *__mptr = (ptr); \
    (type *)((char *)__mptr - offsetof(type, member));})

/* 连接XY */
#define JOIN_XY(X, Y) X##Y

/* EXPAND AND JOIN：把宏展开后再连接 */
#define EXP_AND_JOIN(X, Y) JOIN_XY(X, Y)

/* 静态断言检查 */
#define STATIC_ASSERT(v) enum {EXP_AND_JOIN(_static_assert_, __LINE__) = 1 / (v)}

/* 数组大小 */
#define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))

/* 判断是否为2的幂 */
#define IS_POWER2(n) (n != 0 && (n & (n - 1)) == 0)

#define MACRO_ASSERT(e) assert(e);

#define READ_ONCE(var) (*((volatile typeof(var) *)(&(var))))
#define WRITE_ONCE(var, val)  (*((volatile typeof(val) *)(&(var))) = (val))

#define MACRO_STRINGIFY(var) (var ? #var : #var) /* 在编辑器中高亮 */

#define CSP_ADD_DBG_CODE(SELF, DBG_CODE) (SELF)->dbgCode[DBG_CODE]++

#ifndef likely
#define likely(x)   __builtin_expect ((x), 1)
#endif /* likely */

#ifndef unlikely
#define unlikely(x) __builtin_expect ((x), 0)
#endif /* unlikely */

#endif //CSP_LIB_CSP_INCLUDE_COMMON_COMMDEF_H
